package cn.silver.module.monitor.service.impl;

import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.silver.framework.core.utils.DateUtils;
import cn.silver.framework.core.utils.MapstructUtils;
import cn.silver.framework.core.utils.ServletUtils;
import cn.silver.framework.core.utils.ip.AddressUtils;
import cn.silver.framework.log.event.LoginEvent;
import cn.silver.framework.mybatis.service.impl.BaseServiceImpl;
import cn.silver.module.monitor.domain.LogLogin;
import cn.silver.module.monitor.mapper.LogLoginMapper;
import cn.silver.module.monitor.bean.LogLoginBean;
import cn.silver.module.monitor.param.LoginParam;
import cn.silver.module.monitor.service.ILogLoginService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;

/**
 * 系统访问日志情况信息 服务层处理
 *
 * @author Silver Zhou
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LogLoginServiceImpl extends BaseServiceImpl<LogLoginMapper, LogLogin, LoginParam, LogLoginBean> implements ILogLoginService {

    /**
     * 记录登录信息
     *
     * @param event 登录事件
     */
    @Async
    @EventListener
    public void recordLogininfor(LoginEvent event) {
        HttpServletRequest request = event.getRequest();
        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        final String ip = JakartaServletUtil.getClientIP(request);
        String address = AddressUtils.getRealAddressByIP(ip);
        String builder = MessageFormat.format("{0}{1}{2}{3}{4}", getBlock(ip), address, getBlock(event.getUserName()),
                getBlock(event.getResult()), getBlock(event.getMessage()));
        // 打印信息到日志
        log.info(builder, event.getArgs());
        LogLoginBean logininfor = MapstructUtils.convert(event, LogLoginBean.class);
        // 获取客户端操作系统
        if (logininfor == null) {
            logininfor = new LogLoginBean();
        }
        logininfor.setIpaddr(ServletUtils.getClientIP());
        logininfor.setOs(userAgent.getOs().getName());
        logininfor.setLoginTime(DateUtils.getNowDate());
        this.insert(logininfor);
    }

    private String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg + "]";
    }

    /**
     * 清空系统登录日志
     */
    @Override
    public void cleanLogininfor(LoginParam param) {
        baseMapper.delete(this.buildQueryWrapper(param));
    }
}
